/**
 * 平台管理系统--教师管理
 * @author 卢凤丹
 */
import { Component, OnInit } from '@angular/core';
import { PageEntity } from '../../../core/domain/page.entity';
import { TeacherService } from './teacher.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Observable, Observer } from 'rxjs';
import { HTTP_BASE_URL, SERVERS_NAME } from '../../../config/config';
import { StorageUtil } from '../../../utils/storage.util';
import { SelfValidators } from '../../../utils/self.validators';
import { StatusEnum } from '../../../core/enum/status.enum';
import { FilterEnum, FilterTypeEnum } from '../../../core/enum/filter.enum';
import { NzMessageService, UploadFile } from 'ng-zorro-antd';
import { OtherUtil } from '../../../utils/other.util';
import { SourceServer } from '../../../common/source.server';
import {PostDown} from '../../../utils/postdown';

@Component({
  selector: 'app-teacher',
  templateUrl: './teacher.component.html',
  styleUrls: ['./teacher.component.scss'],
  providers: [TeacherService, SourceServer, PostDown]
})
export class TeacherComponent implements OnInit {
  searchName = '';
  searchNum = '';
  pageInfo: PageEntity = new PageEntity();
  allList: TeacherObj[] = [];
  displayList = [];
  mapOfCheckedId: { [key: string]: boolean } = {};
  isAllCheck = false;
  isIndeterminate = false;
  roleManager = null;

  isAdd = true;
  showAddModal = false; // 新增弹框
  publishModal = false; // 分配角色弹框
  modalTitle = '新增';
  list = [];
  positionList = [];
  titleList = [];
  workTypeList = [];
  // 图片上传
  headerInfo = null;
  uploadUrl = `${SERVERS_NAME.UPLOAD_URL}`;
  validateForm: FormGroup;
  loading = false;
  avatarUrl: string;
  userPhoto = 'assets/user/photo0.png';
  nodes = [];
  // 表格上的过滤
  filterSexArr = [
    {
      text: '男',
      value: 0
    },
    {
      text: '女',
      value: 1
    }
  ];
  filterTypeArr = [
    {
      text: '专技',
      value: 0
    },
    {
      text: '工勤',
      value: 1
    },
    {
      text: '管理',
      value: 2
    },
    {
      text: '中干',
      value: 3
    }
  ];
  filterPositionArr = [];
  filterTitleArr = [];
  filterWorkTypeArr = [];
  searchDepart = null;
  temparr = []; // 用于存储分配角色的临时arr;
  roleId = '';
  canDelete = true;


  // excel导入
  fileListImport: UploadFile[] = [];
  showExcelModal = false;
  headerInfoExcel = null;

  // 导入的Excel 名称
  importExcelName = '';
  previewImage: string | undefined = '';
  previewVisible = false;
  showUploadList = {
    showPreviewIcon: true,
    showRemoveIcon: true,
    hidePreviewIconInNonImage: true
  };


  constructor(
    private service: TeacherService,
    private fb: FormBuilder,
    private source: SourceServer,
    private message: NzMessageService,
    private postDown: PostDown) {
  }

  ngOnInit() {
    this.getPage();
    this.initForm();
    this.departList();

    // this.roleManager = StorageUtil.getLocalStorage('roleManager');
    // 图片上传头部
    const token = StorageUtil.getLocalStorage('token');
    this.headerInfo = {
      Authorization: token,
      enctype: 'multipart/form-data'
    };
    this.searchPosition();
    this.searchTitle();
    this.searchWorkType();

    // 查询过滤的列表
    this.searchMore();

    // 图片上传头部
    this.headerInfoExcel = StorageUtil.getFileHeader();
  }

  checkDelete(): void {
    this.canDelete = OtherUtil.deleteIds(this.mapOfCheckedId).length <= 0;
  }

  initForm() {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      number: [null, [Validators.required, Validators.minLength(6), Validators.maxLength(10)]],
      orgId: [null, [Validators.required]],
      position: ['', [Validators.required]],
      workType: ['', [Validators.required]],
      title: ['', [Validators.required]],
      type: [0, [Validators.required]],
      telphone: [null, []],
      sex: [0, []],
      photo: [null, []],
      id: [null, []],
      email: [null, [SelfValidators.emailValidator]]
    });
  }

  // 表格过滤
  filterSome(event, flag) {
    event.length > 0 ? this.dealLogic(event, flag) : this.pageInfo.filters[flag] = undefined;
    this.getPage();
  }

  dealLogic(event: any, flag: any): void {
    this.pageInfo.first = 1;
    this.pageInfo.filters[flag] = {
      matchMode: FilterEnum.IN,
      value: event.join(','),
      whereType: FilterTypeEnum.AND
    };
  }

  searchByDepart() {
    if (this.searchDepart) {
      this.pageInfo.first = 1;
      this.pageInfo.filters['orgName'.toString()] = {
        matchMode: FilterEnum.CONTAINS,
        value: this.searchDepart
      };
    } else {
      this.pageInfo.filters['orgName'.toString()] = undefined;
    }
    this.getPage();
    this.searchDepart = null;
  }

  resetDepart() {
    this.pageInfo = new PageEntity();
    this.searchDepart = null;
    this.pageInfo.first = 1;
    this.pageInfo.filters['orgName'.toString()] = undefined;
    this.getPage();
  }

  // 查询过滤的职务/职称/任职类型
  async searchMore() {
    let arrObj: Array<{ arrName: Array<any>, strName: string }> = [];
    arrObj = [
      {
        arrName: this.filterPositionArr,
        strName: 'teacher-position'
      },
      {
        arrName: this.filterTitleArr,
        strName: 'teacher-title'
      },
      {
        arrName: this.filterWorkTypeArr,
        strName: 'teacher-workType'
      }
    ];
    // @ts-ignore
    this.filterPositionArr = await this.dealComRequest(arrObj[0].arrName, arrObj[0].strName);
    // @ts-ignore
    this.filterTitleArr = await this.dealComRequest(arrObj[1].arrName, arrObj[1].strName);
    // @ts-ignore
    this.filterWorkTypeArr = await this.dealComRequest(arrObj[2].arrName, arrObj[2].strName);
  }

  // /**
  //  * 公共处理函数
  //  * @param valConfig:数组参数
  //  * @param strVal:字符参数
  //  */
  dealComRequest(valConfig: Array<any>, strVal: string) {
    return new Promise((resolve, reject) => {
      this.service.threeList(strVal).subscribe(res => {
        if (res.status === StatusEnum.SUCCESS) {
          res.datas ? valConfig = res.datas : valConfig = [];
          resolve(valConfig);
        }
      });
    });
  }

  // 性别转换
  transformSex(par) {
    let aa = '';
    switch (par) {
      case 0:
        aa = '男';
        break;
      case 1:
        aa = '女';
        break;
    }
    return aa;
  }

  // 岗位类型转换
  transformPType(par) {
    let bb = '';
    switch (par) {
      case 0:
        bb = '专技';
        break;
      case 1:
        bb = '工勤';
        break;
      case 2:
        bb = '管理';
        break;
      case 3:
        bb = '中干';
    }
    return bb;
  }

  // 点击查询
  clickSearch() {
    this.pageInfo.first = 1;
    this.dealPageFilterFn(this.pageInfo, this.searchName, 'name', FilterEnum.CONTAINS, FilterTypeEnum.AND);
    this.dealPageFilterFn(this.pageInfo, this.searchNum, 'number', FilterEnum.CONTAINS, FilterTypeEnum.AND);
    this.getPage();
  }

  dealPageFilterFn(pageParam: PageEntity, currVal: any, strVal: string, filterMode: any, typeMode: any): void {
    currVal ? pageParam.filters[strVal.toString()] = { matchMode: filterMode, value: currVal, whereType: typeMode } :
      pageParam.filters[strVal.toString()] = undefined;
  }

  // 点击重置
  resetSearch() {
    this.searchName = null;
    this.searchNum = null;
    this.pageInfo = new PageEntity();
    this.pageInfo.first = 1;
    this.pageInfo.filters['number'.toString()] = undefined;
    this.pageInfo.filters['name'.toString()] = undefined;
    this.getPage();
  }

  // 分页查询
  getPage() {
    this.service.page(this.pageInfo).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.allList = res.datas.data;
        this.pageInfo.totalRecords = res.datas.totalRecords;
      }
    });
  }

  // 第几页
  searchPageIndex(event) {
    this.pageInfo.first = event;
    this.getPage();
  }

  // 每页几条
  searchPageSize(event) {
    this.pageInfo.rows = event;
    this.pageInfo.first = 1;
    this.getPage();
  }

  currentPageDataChange($event): void {
    this.displayList = $event;
    this.refreshStatus();
  }

  refreshStatus(): void {
    this.isAllCheck = this.displayList.every(item => this.mapOfCheckedId[item.id]);
    this.isIndeterminate =
      this.displayList.some(item => this.mapOfCheckedId[item.id]) &&
      !this.isAllCheck;
    this.checkDelete();
  }

  checkAll(value: boolean): void {
    this.displayList.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }

  // 点击删除一个
  deleteOne(id) {
    this.service.delete([id]).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.getPage();
      }
    });
  }

  // 删除所选
  deleteAll() {
    const arr = [];
    for (const val in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[val]) {
        arr[arr.length] = val;
      }
    }
    if (arr.length < 1) {
      this.message.warning('请选择需要删除的记录!');
      return;
    }
    this.service.delete(arr).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.mapOfCheckedId = {};
        this.message.success(res.message);
        this.getPage();
      }
    });
  }

  cancelFn(): void {
    this.canDelete = true;
    this.isAllCheck = false;
    this.mapOfCheckedId = {};
    this.isIndeterminate = false;
  }

  // 点击新增
  clickAdd() {
    this.modalTitle = '新增';
    this.initForm();
    this.isAdd = true;
    this.showAddModal = true;
    this.avatarUrl = null;
    this.changePhoto(0);
  }

  // 男女改变
  changePhoto(event) {
    if (event === 1 || event === '1') {
      this.userPhoto = 'assets/user/photo1.png';
    }
    if (event === 0 || event === '0') {
      this.userPhoto = 'assets/user/photo0.png';
    }
  }

  // 查询部门
  departList() {
    this.service.getDepartment().subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.nodes = res.datas;
      }
    });
  }

  // 查询职务
  searchPosition() {
    this.service.positionList('teacher-position').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.positionList = res.datas;
      }
    });
  }

  // 查询职称
  searchTitle() {
    this.service.positionList('teacher-title').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.titleList = res.datas;
      }
    });
  }

  // 查询任职类型
  searchWorkType() {
    this.service.positionList('teacher-worktype').subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.workTypeList = res.datas;
      }
    });
  }

  beforeUpload = (file: File) => {
    return new Observable((observer: Observer<boolean>) => {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        this.message.warning('图片大小不能超过5M!');
        observer.complete();
        return;
      }
      observer.next(isLt5M);
      observer.complete();
    });
  };

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result.toString()));
    reader.readAsDataURL(img);
  }

  // 上传头像
  handleChange(info): void {
    const { file, type } = info;
    if (type === 'success') {
      const { datas, status } = file.response;
      if (status === StatusEnum.SUCCESS) {
        this.getBase64(file.originFileObj, (img: string) => {
          this.loading = false;
          this.avatarUrl = img;
        });
        this.message.success('头像上传成功！');
        this.validateForm.get('photo').setValue(datas.id);
      } else {
        this.message.warning(file.response);
      }
    }
  }

  // 新增确认
  handleOk() {
    this.validateForm.value.sex = parseInt(this.validateForm.value.sex, 10);
    this.validateForm.value.type = parseInt(this.validateForm.value.type, 10);
    this.isAdd ? this.createFn() : this.updateFn();
  }

  updateFn(): void {
    this.service.update(this.validateForm.value).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.showAddModal = false;
        this.getPage();
        this.message.success(res.message);
      }
    });
  }

  createFn(): void {
    this.service.create(this.validateForm.value).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.showAddModal = false;
        this.getPage();
        this.message.success(res.message);
      }
    });
  }

  // 点击分配角色
  publishMan(id) {
    this.roleId = id;
    this.list = [];
    this.publishModal = true;
    this.getData();
  }

  getData(): void {
    this.service.getRole(this.roleId).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.list = res.datas;
      }
    });
  }

  changeRole(event) {
    this.list.forEach(item => {
      this.temparr.forEach(son => {
        if (item.key === son.key) {
          item.direction = event.to;
        }
      });
    });
  }

  select(event) {
    this.temparr = event.list;
  }

  saveRole() {
    const arr = [];
    if (this.list.length > 0) {
      this.list.forEach(item => {
        if (item.direction === 'right') {
          arr[arr.length] = item.key;
        }
      });
    }
    const request = {
      roleIds: arr,
      userIds: [this.roleId]
    };
    this.service.saveRole(request).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.publishModal = false;
        this.getPage();
        this.message.success('角色分配成功!');
      }
    });
  }

  // 点击编辑
  editUser(obj) {
    this.modalTitle = '编辑';
    this.isAdd = false;
    this.validateForm.get('name').setValue(obj.name);
    this.validateForm.get('number').setValue(obj.number);
    this.validateForm.get('orgId').setValue(obj.orgId);
    this.validateForm.get('position').setValue(obj.position);
    this.validateForm.get('title').setValue(obj.title);
    this.validateForm.get('type').setValue(obj.type);
    this.validateForm.get('telphone').setValue(obj.telphone);
    this.validateForm.get('workType').setValue(obj.workType);
    this.validateForm.get('sex').setValue(obj.sex);
    this.validateForm.get('email').setValue(obj.email);
    this.validateForm.get('photo').setValue(obj.photo);
    this.validateForm.get('id').setValue(obj.id);
    this.showAddModal = true;
    if (obj.photo) {
      this.avatarUrl = `${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}`
        + 'source/view/' + obj.photoSource.moduleName + '/' + obj.photoSource.fileNewName;
    } else {
      this.avatarUrl = null;
      this.changePhoto(obj.sex);
    }
  }

  /**
   * 重置密码
   */
  resetPassword(data: any) {
    this.service.resetPassword(data.id).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success('重置密码成功!');
      } else {
        this.message.error('重置密码失败!');
      }
    });
  }

  /**
   * 导入点击
   */
  uploadTable() {
    this.showExcelModal = true;
    this.importExcelName = '';
  }

  /**
   * 1：导出选中；2：导出当前页；3：导出全部
   */
  exportShow(num: number): void {
    const obj = {
      mode: num,
      pager: {},
      sourceIds: []
    };
    if (num === 1) {
      obj.pager = {};
      obj.sourceIds = Object.keys(this.mapOfCheckedId).filter(k => this.mapOfCheckedId[k] === true);
    } else if (num === 3) {
      obj.pager = this.pageInfo;
      obj.sourceIds = [];
    }
    this.postDown.postDownload('security-server/dietc/sys/teacher/exportExcel2', obj);
  }

  /**
   * 下载模板
   */
  exportExclShow() {
    window.open(`${HTTP_BASE_URL}${SERVERS_NAME.SECURITY_SERVER}sys/teacher/downloadModule`);
  }

  /**
   * 导入确认
   */
  handleUpload() {
    if (!this.fileListImport || this.fileListImport.length === 0) {
      this.message.warning('请选择上传文件!');
      return;
    }
    const formData = new FormData();
    this.fileListImport.forEach((file: any) => {
      formData.append('file', file);
    });
    // 执行导入
    this.service.importExcel(formData).subscribe(res => {
      if (res.status === StatusEnum.SUCCESS) {
        this.message.success('导入成功!');
        this.showExcelModal = false;
        // 清除导入文件id
        this.importExcelName = '';
        this.getPage();
      }
    });
  }

  /**
   * 删除导入文件
   */
  delFile() {
    this.fileListImport = [];
    this.importExcelName = '';
  }

  /**
   * 文件上传前
   * @ param file
   */
  beforeUploadExcel = (file: UploadFile): boolean => {
    this.fileListImport = [];
    this.fileListImport.push(file);
    this.importExcelName = file.name;
    return false;
  };

}

export class TeacherObj {
  email?: string;
  id?: string;
  name?: string;
  number?: string;
  orgId?: string;
  photo?: string;
  photoSource?: any;
  position?: string;
  workType?: string;
  sex = 0;
  telphone?: string;
  title?: string;
  type = 0;
}
